﻿#encoding: utf-8

require 'securerandom'
require 'open-uri'
require 'awesome_print'
require 'json'

def save_url_to_file url, fn
    begin
      URI.open(url) do |file|
          File.open(fn, 'wb') { |local_file| local_file.write(file.read) }
      end
      #open(fn, 'wb') do |file|
      #  file << open(url).read
      #end
    rescue => e
        err_code = e.message.split(' ')
        err = err_code[0].to_i
        #puts "[FAILED] #{e.message} - #{url}"
        return err if err > 0 
        return 839
    end
    return 200
end

#下载远程文件到本地服务器，并返回本地服务器的访问链接地址
def save_url_to_named_file url, named = Time.now.to_date.to_s

    missing = 'missing.png'
    short_url = (url.split('?sign='))[0]

    words = short_url.split('.')
    suffix = words[words.size-1]
    uuid = SecureRandom.uuid
    fn = "#{named}-#{uuid}.#{suffix}"
    fp = "/home/www/tutem_mall/public/uploads/survey/#{fn}"

    res = save_url_to_file url, fp

    puts "convert to :#{fp}"
    link = res == 200 ? "https://mall.totembio.cn/uploads/survey/#{fn}" : "https://mall.totemlife.cn/uploads/survey/#{res}.png"
    return link

end
# puts save_url_to_named_file "http://oms2.totembio.cn/uploads/a.png"

def get_answer_by_id answers, id
    answers.each do |answer|
        return answer if answer['id'].include? id #允许模糊匹配
    end
    return nil
end

def get_texted_answer_by_qid questions, id

    questions.each do |answer|
            if answer['id'].include? id.to_s #允许模糊匹配
            case answer['type']
            when 'datetime', 'text', 'textarea'
                return answer['text']
            when 'radio'
                return answer['options'][0]['text']
            when 'checkbox', 'select'
                options = answer['options']
                opt_idx = 0
                text = ''
                options.each do |opt|
                    text += "、" if opt_idx != 0
                    text += opt['text']
                    opt_idx += 1
                end
                return text
            when 'upload', 'signature'
                files = answer['files']
                f_idx = 0
                text = ''
                files.each do |f|
                    text += "、" if f_idx != 0
                    link = save_url_to_named_file f['url']
                    text += link
                    f_idx += 1
                end
                return text
            else
                return answer.to_s
            end
        end
    end
    return ''
end

#2024H1问卷
def parse_payload_for_14784502 payload

    result = {}
    answers = {}

    questions = payload['answer'][0]['questions']
    @the_questions = questions

    maps = {
        "q-19-lHop"=> {"name"=> "channel", "prefix"=> "经", "suffix"=> "了解，"},
        "q-47-ukAc"=> {"name"=> "stores", "prefix"=> "通过", "suffix"=> "购买或获得；"},
        "q-23-YFj9"=> {"name"=> "user", "prefix"=> "给", "suffix"=> "使用，"},
        "q-24-9lYj"=> {"name"=> "gendar", "prefix"=> "用户性别：", "suffix"=> ", "},
        "q-43-YXTV"=> {"name"=> "group", "prefix"=> "用户年龄：", "suffix"=> "；"},
        "q-33-rfgu"=> {"name"=> "purposes", "prefix"=> "针对疾病：", "suffix"=> ", "},
        "q-44-9rzJ"=> {"name"=> "history", "prefix"=> "疾病时间：", "suffix"=> "，"},
        "q-26-RiSx"=> {"name"=> "diagnosis", "prefix"=> "疾病诊断：", "suffix"=> "，"},
        "q-34-J6UL"=> {"name"=> "therapy", "prefix"=> "治疗方案：", "suffix"=> "；"},
        "q-21-A9V7"=> {"name"=> "goods", "prefix"=> "使用产品：", "suffix"=> "，"},
        "q-28-Q7RD"=> {"name"=> "time", "prefix"=> "使用时长：", "suffix"=> "，"},
        "q-45-QO5Q"=> {"name"=> "serve", "prefix"=> "日均用量：", "suffix"=> "；"},
        "q-36-MSbM"=> {"name"=> "symptoms", "prefix"=> "症状变化：", "suffix"=> "，"},
        "q-37-GpTn"=> {"name"=> "metrics", "prefix"=> "指标变化：", "suffix"=> "，"},
        "q-38-NLsl"=> {"name"=> "proof", "prefix"=> "检测单据：", "suffix"=> "；"},
        "q-39-kAfq"=> {"name"=> "rating", "prefix"=> "总体评价：", "suffix"=> "，"},
        "q-41-aVpx"=> {"name"=> "reason", "prefix"=> "评价原因：", "suffix"=> "；"},
        "q-42-rCbX"=> {"name"=> "question", "prefix"=> "问题留言：", "suffix"=> "，"},
        "q-46-gLt7"=> {"name"=> "shareFurther", "prefix"=> "可做采访：", "suffix"=> "。"},
        "q-40-U2HY"=> {"name"=> "signature", "prefix"=> "授权签名：", "suffix"=> "，"}
    }

    text = ''
    maps.keys.each do |key|
        value = get_texted_answer_by_qid questions, key
        name = maps[key]['name']
        text += maps[key]['prefix'] + value + maps[key]['suffix']
        answers.store name, value
    end

    result.store 'answers', answers
    result.store 'text', text
    return result

end

payload_json = '
    {"survey_id":"14784502","answer_id":"3","qq":"60097891622","respondent_id":"60097891622","respondent_type":"微信","openid":"","weixin_openid":"o86_0jjTY4hRW9pG5kb_pYHcapMU","started_at":"2024-06-15 20:58:52","ended_at":"2024-06-15 20:59:19","duration":"27","answer":[{"id":"p-1-baf5","questions":[{"id":"q-19-lHop","type":"select","options":[{"id":"o-3-lNo7","checked":"1","text":"销售机构推广","sort_no":"0"}]},{"id":"q-47-ukAc","type":"checkbox","options":[{"id":"o-101-4be2","checked":"1","text":"图腾生命医学","sort_no":"0"},{"id":"o-104-48e9","checked":"1","text":"图腾生命科学","sort_no":"0"}],"blanks":[]},{"id":"q-23-YFj9","type":"select","options":[{"id":"o-102-fc51","checked":"1","text":"家属","sort_no":"0"}]},{"id":"q-24-9lYj","type":"select","options":[{"id":"o-101-3cb0","checked":"1","text":"男","sort_no":"0"}]},{"id":"q-43-YXTV","type":"select","options":[{"id":"o-104-3cc1","checked":"1","text":"28-中年 [28~65岁)","sort_no":"0"}]},{"id":"q-33-rfgu","type":"select","options":[{"id":"o-148-dd9b","checked":"1","text":"[其它亚健康调理] 其它亚健康调理","sort_no":"0"}]},{"id":"q-44-9rzJ","type":"select","options":[{"id":"o-105-1004","checked":"1","text":"24-24个月以上未满36个月","sort_no":"0"}]},{"id":"q-34-J6UL","type":"text","text":"非布司他每天半科"},{"id":"q-21-A9V7","type":"checkbox","options":[{"id":"o-101-74f2","checked":"1","text":"图腾益生","sort_no":"0"},{"id":"o-102-3eb6","checked":"1","text":"图腾益生液","sort_no":"0"},{"id":"o-104-b0c2","checked":"1","text":"图腾益仙","sort_no":"0"}],"blanks":[]},{"id":"q-28-Q7RD","type":"select","options":[{"id":"o-107-842d","checked":"1","text":"24-已满24个月不足36个月","sort_no":"0"}]},{"id":"q-45-QO5Q","type":"select","options":[{"id":"o-103-204e","checked":"1","text":"2-每天2支","sort_no":"0"}]},{"id":"q-36-MSbM","type":"text","text":"头发掉了"},{"id":"q-37-GpTn","type":"text","text":"血象好了"},{"id":"q-39-kAfq","type":"select","options":[{"id":"o-104-785d","checked":"1","text":"2-非常有用","sort_no":"0"}]},{"id":"q-41-aVpx","type":"textarea","text":"谁用谁知道"},{"id":"q-42-rCbX","type":"textarea","text":"还要吃多久"},{"id":"q-46-gLt7","type":"select","options":[{"id":"o-0-ZwrF","checked":"1","text":"是","sort_no":"0"}]},{"id":"q-40-U2HY","type":"signature","text":"","signature_id":"1MrYaz54rq","expired":"10m","files":[{"name":"1MrYaz54rq.png","url":"https://wj-collection-1258344706.cos-website.ap-guangzhou.myqcloud.com/formal/14784502/signatures/1MrYaz54rq.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKID3dz5uN4cMpGamjMvBaySkOoxwmMgMacO%26q-sign-time%3D1718456300%3B1718456960%26q-key-time%3D1718456300%3B1718456960%26q-header-list%3Dhost%26q-url-param-list%3D%26q-signature%3D6284fa11688ba30a3f5db4bb220c666366590f9d&response-content-disposition=attachment%3B1MrYaz54rq.png"}]}]},{"id":"custom_args","questions":[{"id":"custom-arg-01","type":"text","text":"36","title":"uid","sub_type":"0","description":"用户ID，传递用户身份信息"}]}],"score":"","country":"中国","province":"广东省","city":"广州市","ip":"2409:895a:c88:8f4d:d474:e1ff:fe26:3359","ua":"Mozilla/5.0 (Linux; Android 13; 2312CRAD3C Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220099 MMWEBSDK/20240404 MMWEBID/9083 MicroMessenger/8.0.49.2600(0x28003157) WeChat/a","referrer":"","whitelist_name":"","weixin_tp_openid":"o86_0jjTY4hRW9pG5kb_pYHcapMU"}
'

payload = JSON.parse payload_json
result = parse_payload_for_14784502 payload
ap result
